import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/transaction_password_page.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';

final GlobalController globalController = Get.find();

//售卖弹窗
Future<void> showSaleCollectionSheet({
  required TextEditingController saleController,
  required List<String> dataList,
  required int collectionId,
  String sxf = '0',
}) async {
  // saleController.text  = '';
  getPrice(
    dataList: dataList,
    collectionId: collectionId,
    saleController: saleController,
  );
  showModalBottomSheet(
    context: Get.context!,
    isDismissible: false,
    isScrollControlled: true,

    backgroundColor: Color.fromRGBO(0, 0, 0, 0),
    builder: (BuildContext context) {
      return BottomSheet(
        onClosing: () {},
        enableDrag: false, // 禁止拖拽，否则报错
        backgroundColor: Color.fromRGBO(59, 62, 69, 1),
        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.fromLTRB(
              0,
              0,
              0,
              MediaQuery.of(context).viewInsets.bottom,
            ),

            // height: MediaQuery.of(context).size.height,
            height:
                400.px +
                (globalController.isFocused.value
                    ? MediaQuery.of(context).viewInsets.bottom
                    : 0),
            constraints: BoxConstraints(minHeight: 400.px, maxHeight: 800.px),
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(color: Colors.transparent),
            // clipBehavior: Clip.antiAlias,
            child: Stack(
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Container(
                        clipBehavior: Clip.antiAlias,
                        decoration: BoxDecoration(
                          color: Color.fromRGBO(59, 62, 69, 1),

                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(12.px),
                            topRight: Radius.circular(12.px),
                          ),
                        ),
                        child: ListView(
                          children: [
                            SizedBox(
                              width: context.width,
                              height: 54.px,
                              child: Stack(
                                children: [
                                  Center(
                                    child: Text(
                                      '出售',
                                      style: TextStyle(
                                        color: AppColors.fontColor,
                                        fontSize: 17.px,
                                        fontWeight: FontWeight.w500,
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                  Positioned(
                                    top: 18.px,
                                    right: 18.px,
                                    child: GestureDetector(
                                      onTap: () {
                                        Navigator.of(context).pop();
                                      },
                                      child: Icon(
                                        Icons.close,
                                        color: Color.fromRGBO(196, 196, 196, 1),
                                        size: 20.px,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(14.px, 0, 14.px, 0),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: EdgeInsets.only(
                                      left: 10.px,
                                      right: 10.px,
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '出售价格',
                                          style: TextStyle(
                                            color: AppColors.fontColor,
                                            fontSize: 14.px,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            showSheet(isOnlyShow: true);
                                          },
                                          child: Row(
                                            children: [
                                              Text(
                                                '寄售说明',
                                                style: TextStyle(
                                                  color:
                                                      AppColors.fontColorGray99,
                                                  fontSize: 12.px,
                                                ),
                                              ),
                                              hiSpace(width: 2.px),
                                              ImageAssetWidget(
                                                imageUrl:
                                                    'static/images/right_ico.png',
                                                height: 14.px,
                                                width: 14.px,
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 8.px),
                                  InputWidget(
                                    focusNode: globalController.focusNode,
                                    controller: saleController,
                                    maxLength: 6,
                                    fontColor: AppColors.startColor,
                                    inputType: TextInputType.numberWithOptions(
                                      decimal: true,
                                    ),

                                    hint: '请输入价格',
                                    inputFormatters: [
                                      FilteringTextInputFormatter(
                                        RegExp("[0-9.]"),
                                        allow: true,
                                      ),
                                      MyNumberTextInputFormatter(digit: 2),
                                    ],
                                    buttonRadio: 100,
                                    backgroundColor:
                                        AppColors.backgroundColorBlack,
                                    onChanged: (value) {
                                      // controller.invitedCode.value = value;
                                      globalController.timer?.cancel();
                                      globalController.timer = Timer(
                                        Duration(seconds: 2),
                                        () {
                                          if (value == '') {
                                            return;
                                          }
                                          getPrice(
                                            dataList: dataList,
                                            collectionId: collectionId,
                                            saleController: saleController,
                                          );
                                        },
                                      );
                                    },
                                  ),
                                  SizedBox(height: 20.px),
                                  Padding(
                                    padding: EdgeInsets.only(
                                      left: 10.px,
                                      right: 10.px,
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          '寄售手续费',
                                          style: TextStyle(
                                            color:
                                                AppColors.backgroundColorGrey,
                                            fontSize: 14.px,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                        Text(
                                          '${'${num.parse(sxf) * 100}'.toString()}%',
                                          style: TextStyle(
                                            color: AppColors.fontColor,
                                            fontSize: 14.px,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 20.px),
                                  Padding(
                                    padding: EdgeInsets.only(
                                      left: 10.px,
                                      right: 10.px,
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          '出售数量',
                                          style: TextStyle(
                                            color:
                                                AppColors.backgroundColorGrey,
                                            fontSize: 14.px,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                        Text(
                                          '${dataList.length}',
                                          style: TextStyle(
                                            color: AppColors.fontColor,
                                            fontSize: 14.px,
                                            fontWeight: FontWeight.w500,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 20.px),
                                  Obx(() {
                                    return Padding(
                                      padding: EdgeInsets.only(
                                        left: 10.px,
                                        right: 10.px,
                                      ),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Text(
                                            '到账金额',
                                            style: TextStyle(
                                              color:
                                                  AppColors.backgroundColorGrey,
                                              fontSize: 14.px,
                                              fontWeight: FontWeight.w500,
                                            ),
                                            textAlign: TextAlign.left,
                                          ),
                                          Text(
                                            globalController.priceGet.value,
                                            style: TextStyle(
                                              color: AppColors.fontColor,
                                              fontSize: 14.px,
                                              fontWeight: FontWeight.w500,
                                            ),
                                            textAlign: TextAlign.left,
                                          ),
                                        ],
                                      ),
                                    );
                                  }),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '*超出挂单时间后，无法取消出售',
                          style: TextStyle(
                            color: Color.fromRGBO(57, 231, 255, 0.5),
                            fontSize: 12.px,
                          ),
                        ),
                        Container(
                          color: Color.fromRGBO(59, 62, 69, 1),
                          height: 60.px,
                          child: Center(
                            child: ButtonWidget(
                              label: '确认出售',
                              width: 322.px,
                              height: 46.px,
                              contentType: ContentType.text,

                              fontWeight: FontWeight.bold,
                              fontSize: 15.px,
                              fontColor: AppColors.backgroundColorBlack,
                              onPressed: () {
                                if (saleController.text == '') {
                                  showToast('请输入价格');
                                  return;
                                }
                                getIncubationReminder().then(
                                  (res) => {
                                    if (res.data)
                                      {
                                        showSheet(
                                          dataList: dataList,
                                          collectionId: collectionId,
                                          saleController: saleController,
                                        ),
                                      }
                                    else
                                      {
                                        passwordDialog(
                                          dataList,
                                          collectionId,
                                          saleController,
                                        ),
                                      },
                                  },
                                );
                                //
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          );
        },
      );
    },
  );
}

passwordDialog(dataList, collectionId, saleController) {
  if (globalController.user.value?.transactionPassword == null) {
    showConfirmDialog(
      context: Get.context!,
      message: '请先设置交易密码',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(label: '取消', onPressed: () {}),
        ActionModel(
          label: '前往设置',
          onPressed: () {
            Get.toNamed(ChangeExchangePassword.path);
          },
        ),
      ],
    );
    return;
  }
  TransactionPasswordDialog.show(
    Get.context!,
    onCompleted: (password) {
      saleList(
        dataList: dataList,
        collectionId: collectionId,
        password: password,
        saleController: saleController,
      );
    },
    onCancel: () {},
  );
}

//弹窗
Future<void> showSheet({
  dataList,
  collectionId,
  saleController,
  isOnlyShow,
}) async {
  showModalBottomSheet(
    context: Get.context!,
    isDismissible: false,
    isScrollControlled: true,
    backgroundColor: Color.fromRGBO(0, 0, 0, 0),
    builder: (BuildContext context) {
      return BottomSheet(
        onClosing: () {},
        enableDrag: false, // 禁止拖拽，否则报错
        backgroundColor: Color.fromRGBO(59, 62, 69, 1),

        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.fromLTRB(
              0,
              0,
              0,
              MediaQuery.of(context).viewInsets.bottom,
            ),
            height: 608.px,
            constraints: BoxConstraints(minHeight: 400.px, maxHeight: 800.px),
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(color: Colors.transparent),
            child: Stack(
              children: [
                SizedBox(
                  width: context.width,
                  height: 54.px,
                  child: Stack(
                    children: [
                      Center(
                        child: Text(
                          '寄售说明',
                          style: TextStyle(
                            color: AppColors.fontColor,
                            fontSize: 16.px,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      Positioned(
                        top: 0.px,
                        left: 18.px,
                        bottom: 0.px,
                        child: GestureDetector(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Center(
                            child: Icon(
                              Icons.keyboard_arrow_left,
                              color: AppColors.fontColor,
                              size: 26.px,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(top: 54.px),
                        clipBehavior: Clip.antiAlias,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(12.px),
                            topRight: Radius.circular(12.px),
                          ),
                        ),
                        child: ListView(
                          children: [
                            Container(
                              padding: EdgeInsets.fromLTRB(
                                14.px,
                                0,
                                14.px,
                                40.px,
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Obx(() {
                                    return Padding(
                                      padding: EdgeInsets.only(
                                        left: 10.px,
                                        right: 10.px,
                                      ),
                                      child: Text(
                                        '${globalController.staticInfo.value!.consignmentNotice}',
                                        style: TextStyle(
                                          color: AppColors.fontColorB2,
                                          fontSize: 14.px,
                                        ),
                                      ),
                                    );
                                  }),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    isOnlyShow != true
                        ? Padding(
                          padding: EdgeInsets.all(14.px),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              ButtonWidget(
                                label: '不再提醒',
                                width: 169.px,
                                height: 40.px,
                                fontSize: 16.px,
                                fontColor: AppColors.fontColorSearch,
                                bgColorStart: Color.fromRGBO(59, 62, 69, 1),
                                bgColorEnd: Color.fromRGBO(59, 62, 69, 1),
                                border: Border.all(
                                  width: 1.px,
                                  color: AppColors.fontColorSearch,
                                ),
                                onPressed: () {
                                  updateIncubationReminder(
                                    'NO_MORE_REMIND',
                                    dataList,
                                    collectionId,
                                    saleController,
                                    isOnlyShow,
                                  );
                                },
                              ),
                              ButtonWidget(
                                label: '下次提醒',
                                width: 169.px,
                                height: 40.px,
                                fontSize: 16.px,
                                fontColor: AppColors.fontColor21,
                                onPressed: () {
                                  updateIncubationReminder(
                                    'NEXT_REMIND',
                                    dataList,
                                    collectionId,
                                    saleController,
                                    isOnlyShow,
                                  );
                                },
                              ),
                            ],
                          ),
                        )
                        : SizedBox(),
                  ],
                ),
              ],
            ),
          );
        },
      );
    },
  );
}

saleList({
  required List<String> dataList,
  required int collectionId,
  required String password,
  required TextEditingController saleController,
}) {
  if (saleController.text == '') {
    showToast('请输入出售价格');
    return;
  }
  http.netFetch<dynamic>(
    ProductApi.createSaleOrder,
    params: {
      'userCollectionIds': dataList,
      'collectionId': collectionId,
      'payPassword': password,
      'salePrice': saleController.text,
    },
    method: Method.post,
    success: (result) {
      if (result.code == 200) {
        Navigator.of(Get.context!).pop();
        showToast('已上架待售出');
      }
    },
  );
}

//获取金额
getPrice({
  required List<String> dataList,
  required int collectionId,
  required TextEditingController saleController,
}) {
  http.netFetch<dynamic>(
    ProductApi.getSaleOrderPrice,
    params: {
      'userCollectionIds': dataList,
      'collectionId': collectionId,
      'salePrice': saleController.text,
    },
    method: Method.post,
    success: (result) {
      if (result.code == 200) {
        GlobalController globalController = Get.find();
        consoleLog('${result.data['receivedAmount']}jiage');
        globalController.priceGet.value = result.data['receivedAmount'];
      }
    },
  );
}

Future<dynamic> getIncubationReminder() async {
  return http.netFetch<dynamic>(
    ProductApi.getIncubationReminder,
    params: {},
    method: Method.get,
    success: (result) {},
  );
}

updateIncubationReminder(
  status,
  dataList,
  collectionId,
  saleController,
  isOnlyShow,
) {
  http.netFetch<dynamic>(
    ProductApi.updateIncubationReminder,
    params: {"reminderStatus": status},
    method: Method.post,
    success: (result) {
      Navigator.of(Get.context!).pop();
      if (isOnlyShow != true) {
        passwordDialog(dataList, collectionId, saleController);
      }
    },
  );
}

class MyNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  ///允许的小数位数，-1代表不限制位数
  int digit;
  MyNumberTextInputFormatter({this.digit = -1});
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value == "-") {
      value = "-";
      selectionIndex++;
    } else if (value != "" &&
            value != defaultDouble.toString() &&
            strToFloat(value, defaultDouble) == defaultDouble ||
        getValueDigit(value) > digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
